package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"post-admin/cache"
	"post-admin/models"
	"time"
)

func PostList(c *gin.Context) {
	var posts []models.Post
	list_key := "list_key"
	cachejson, _ := cache.Rdb.Get(cache.Ctx, list_key).Result()
	if cachejson == "" {
		models.DB.Find(&posts)
		cachedata, _ := json.Marshal(posts)
		cache.Rdb.Set(cache.Ctx, list_key, cachedata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &posts)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": posts,
	})
	return
}
func PostDetail(c *gin.Context) {
	id := c.Query("id")
	var post models.Post
	detail_key := "detail_key" + id
	cachejson, _ := cache.Rdb.Get(cache.Ctx, detail_key).Result()
	if cachejson == "" {
		models.DB.Where("id=?", id).First(&post)
		cachedata, _ := json.Marshal(post)
		cache.Rdb.Set(cache.Ctx, detail_key, cachedata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &post)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
	})
	return
}
